export default {
  // 为当前模块开启命名空间
  namespaced: true,
  // 模块的 state 数据
  state: () => ({
    // 存储每个商品的信息对象
    //包括：goods_id, goods_name, goods_price, goods_count, goods_small_logo,goods_state
    cart: JSON.parse(uni.getStorageSync('cart') || '[]')
  }),
  // 模块的 mutations 方法
  mutations: {
    addToCart(state, goods) {
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
      if (!findResult) {
        state.cart.push(goods)
      } else {
        findResult.goods_count++
      }
      // console.log(findResult)
      // console.log(state.cart)
      // 本地持久化存储
      this.commit('m_cart/saveToStorage')

    },
    saveToStorage(state) {
      uni.setStorageSync('cart', JSON.stringify(state.cart))
    },
    updateGoodsState(state, goods) {
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
      if (findResult) {
        findResult.goods_state = goods.goods_state
      }
      // console.log(state.cart)
      this.commit('m_cart/saveToStorage')
    },
    updateGoodsNum(state, goods) {
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
      if (findResult) {
        // 更新对应商品的数量
        findResult.goods_count = goods.goods_count
        // 更新的最新数据持久化存储到本地缓存
        this.commit('m_cart/saveToStorage')
      }
      // console.log(state.cart)
    },
    deleteGoods(state, goods) {
      // 过滤出不被删掉的商品
      state.cart = state.cart.filter(x => x.goods_id !== goods.goods_id)
      // 把最新的数据进行本地存储
      this.commit('m_cart/saveToStorage')
    },
    updateAllGoodsState(state, newState) {
      // 改变购物车所有商品的勾选状态
      state.cart.forEach(item => item.goods_state = newState)
      // 持久化存储
      this.commit('m_cart/saveToStorage')
    }
  },
  // 模块的 getters 属性
  getters: {
    // 购物车中的商品总数量
    total(state) {
      //   let c = 0
      // state.cart.forEach( x => c += x.goods_count)
      // return c
      return state.cart.reduce((total, item) =>
        total += item.goods_count, 0)
    },
    // 购物车中被勾选的商品数量
    checkedCount(state) {
      return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count, 0)
    },

    // 购物车中已勾选的商品价格总和
    checkedGoodsAmount(state) {
      return state.cart.filter(x => x.goods_state === true).reduce((totalamount, item) => {
        return totalamount += item.goods_count * item.goods_price
      }, 0).toFixed(2)
    },
    // 全选框的选中状态
    allChecked(state) {
      return state.cart.every(x => x.goods_state)
    }
  }
}
